package com.jiangdong.craft.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
@org.aspectj.lang.annotation.Aspect
public class Aspect {

    @Autowired
    HttpServletRequest request;

    private Logger logger = LoggerFactory.getLogger(Aspect.class);

    private Long time;

    @Pointcut("execution(* com.jiangdong.craft.service..*.*(..))")
    public void pointerCu(){
    }

    @Before("pointerCu()")
    public void before(JoinPoint joinPoint){
        System.out.println("-------------method before-------------------");
        time = System.currentTimeMillis();
        logger.info(joinPoint.getSignature().getName() + "被调用,请求ip为"+getIp());
    }

    @AfterReturning(pointcut = "pointerCu()",returning = "res")
    public void after(JoinPoint joinPoint,Object res){
        long responseTime = System.currentTimeMillis() - time;
        logger.info("方法:" + joinPoint.getSignature().getName() + "返回值:" + res + ",响应时间:" + responseTime + "ms");
        System.out.println("-------------method after---------------------");
    }

    @AfterThrowing(pointcut = "pointerCu()",throwing="a")
    public void exceptionMessage(Throwable a){
        logger.error("出现异常:" + a.getMessage()+ "cause:" + a.getCause());
        System.out.println("-------------method error---------------------");
    }

    public String getIp(){
        String ip = request.getHeader("x-forwarded-for");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
        }
        return ip;
    }

}
